package com.kaili.tms.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.common.exception.BaseExcept;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.tms.exception.ResponseStatus;
import com.kaili.tms.mapper.ExpenseAccountMapper;
import com.kaili.tms.pojo.dto.CostStatisticsQueryDTO;
import com.kaili.tms.pojo.dto.ExpenseAccountQueryDTO;
import com.kaili.tms.pojo.entity.*;
import com.kaili.tms.pojo.vo.CostStatisticsDetailVO;
import com.kaili.tms.pojo.vo.CostStatisticsVO;
import com.kaili.tms.pojo.vo.ExpenseAccountVO;
import com.kaili.tms.service.BaseFeignService;
import com.kaili.tms.service.ExpenseAccountService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: renzhikun
 * @Time: 19-1-25 下午1:46
 * @Copyright: ©  杭州凯立通信有限公司 版权所有
 * @Warning: 本内容仅限于公司内部传阅, 禁止外泄或用于其它商业目的
 */
@Service
public class ExpenseAccountServiceImpl implements ExpenseAccountService {

    @Autowired
    private ExpenseAccountMapper expenseAccountMapper;
    @Autowired
    private BaseFeignService feignService;

    @Override
    public void addExpenseAccount(ExpenseAccount expenseAccount) {
        expenseAccount.setCreateBy(LoginDetailUtils.getCurrentEmployeeId());
        expenseAccount.setCreateTime(new Date());
        expenseAccountMapper.addExpenseAccount(expenseAccount);
    }

    @Override
    public void updateExpenseAccount(ExpenseAccount expenseAccount) {

        if (expenseAccount.getStatus() != null && expenseAccount.getStatus() == 1) {
            expenseAccount.setAuditBy(LoginDetailUtils.getCurrentEmployeeId());
            expenseAccount.setAuditTime(new Date());
        } else if(expenseAccount.getStatus() != null && expenseAccount.getStatus() == 2) {
            expenseAccount.setSettleBy(LoginDetailUtils.getCurrentEmployeeId());
            expenseAccount.setSettleTime(new Date());
        } else if(expenseAccount.getStatus() != null && expenseAccount.getStatus() == 3) {
            expenseAccount.setModifyBy(LoginDetailUtils.getCurrentEmployeeId());
            expenseAccount.setModifyTime(new Date());
        }
        expenseAccountMapper.updateExpenseAccount(expenseAccount);
    }

    @Override
    public Page<ExpenseAccountVO> queryExpenseAccount(Page<ExpenseAccountVO> page, ExpenseAccountQueryDTO queryDTO) {
        List<ExpenseAccountVO> list = expenseAccountMapper.queryExpenseAccount(page, queryDTO);
        return page.setRecords(list);
    }

    @Override
    public List<ExpenseAccountExport> expenseAccountExport(Map<String, Object> map) {
        return expenseAccountMapper.expenseAccountExport(map);
    }

    @Override
    @Transactional
    public void doImPort(List<ExpenseAccountExport> org) {
        try {
            ExpenseAccount expenseAccount = new ExpenseAccount();
            for (ExpenseAccountExport accountExport : org) {
                expenseAccount.setInvoiceCode(accountExport.getInvoiceCode());
                Map invoiceType  = feignService.dictService(accountExport.getInvoiceType());
                expenseAccount.setInvoiceType(Integer.valueOf(invoiceType.get("data").toString()));

                expenseAccount.setAccount(Double.valueOf(accountExport.getAccount()));
                switch (accountExport.getStatus()) {
                    case "作废":
                        expenseAccount.setStatus(3);
                        break;
                    case "审核未结算":
                        expenseAccount.setStatus(2);
                        break;
                    case "已结算":
                        expenseAccount.setStatus(1);
                        break;
                    case "未审核":
                        expenseAccount.setStatus(0);
                        break;
                    default:
                        throw new BaseExcept(ResponseStatus.EXPENSE_STATUS);
                }

                Map driver  = feignService.selectBaseDriverByName(accountExport.getApplyBy());
                expenseAccount.setApplyBy(Integer.valueOf(driver.get("data").toString()));

                Map applyType  = feignService.dictService(accountExport.getApplyType());
                expenseAccount.setApplyType(Integer.valueOf(applyType.get("data").toString()));

                Map car = feignService.queryBaseCar(accountExport.getCarCode());
                expenseAccount.setCarCode(Integer.valueOf(car.get("data").toString()));

                expenseAccount.setCreateDate(accountExport.getCreateDate());
                expenseAccount.setLineNum(accountExport.getLineNum());
                expenseAccount.setTrainNum(accountExport.getTrainNum());

                Map provenance =  feignService.queryCityName(accountExport.getProvenance());
                expenseAccount.setProvenance(Integer.valueOf(provenance.get("data").toString()));
                Map destination = feignService.queryCityName(accountExport.getDestination());
                expenseAccount.setDestination(Integer.valueOf(destination.get("data").toString()));

                Map payment  = feignService.dictService(accountExport.getPayment());
                expenseAccount.setPayment(Integer.valueOf(payment.get("data").toString()));

                Map site = feignService.querySiteName(accountExport.getSite());
                expenseAccount.setSite(Integer.valueOf(site.get("data").toString()));

                ExpenseAccount account = selectExpenseAccount(expenseAccount);
                if (account != null) {
                    updateExpenseAccount(account);
                }else {
                    addExpenseAccount(expenseAccount);
                }
            }
        }catch (Exception e){
            throw new BaseExcept(ResponseStatus.IMPORT_EXCEPTION);
        }

    }

    @Override
    public ExpenseAccount selectExpenseAccount(ExpenseAccount expenseAccount) {
        return expenseAccountMapper.selectExpenseAccount(expenseAccount);
    }


    @Override
    //Map<String,List<costStatisticsEntity>>
    //    arr    []
    //           time : 2018-01
    //           value:List<CostStatisticsVO>
    public Map<String,List<costStatisticsEntity>> querySixMonthCostStatistics(CostStatisticsQueryDTO queryDTO) {
        //获取指定时间的前六个月日期
        java.util.Calendar cal = java.util.Calendar.getInstance();
        String[] lastSixMonths = new String[6];
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date date = sdf.parse(queryDTO.getStartTime());
            cal.setTime(date);
            String str = (new SimpleDateFormat("yyyy-MM")).format(cal.getTime());
            lastSixMonths[0] = str;
            for (int i=1;i<=5;i++){
                cal.add(java.util.Calendar.MONTH,-1);
                String str2 = (new SimpleDateFormat("yyyy-MM")).format(cal.getTime());
                lastSixMonths[i] = str2;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        //获取这六个月之间的数据
        CostStatisticsQuery costStatistics = new CostStatisticsQuery();
        BeanUtils.copyProperties(queryDTO,costStatistics);
        costStatistics.setStartTime(lastSixMonths[0]);
        costStatistics.setBeforeTime(lastSixMonths[5]);
        List<CostStatisticsVO> list = expenseAccountMapper.querySixMonthCostStatistics(costStatistics);

        Map<String,List<costStatisticsEntity>> returnMap = new HashMap<>();
        List<costStatisticsEntity> listEntity = new ArrayList<>();
        costStatisticsEntity entity;
        //编历 根据月份分组
        Map<String,List<CostStatisticsVO>> map = new HashMap<>();
        List<CostStatisticsVO> VOList;
        for (int i = 0; i <lastSixMonths.length ; i++) {
            VOList = new ArrayList<>();
            entity = new costStatisticsEntity();
            //计算第一个月份的成本百分比
            if(i == 1){ //说明第一个月份的数据已经分组完毕
                //先计算第一个月的总金额
                Double totalMoney = 0d;
                for (CostStatisticsVO VO:map.get(lastSixMonths[0])) {
                    totalMoney = totalMoney + VO.getAccount();
                }
                //依次计算该成本类型的金额占比
                BigDecimal b2 = new BigDecimal(totalMoney.toString());
                for (CostStatisticsVO VO:map.get(lastSixMonths[0])) {
                    BigDecimal b1 = new BigDecimal(VO.getAccount().toString());
                    VO.setPrecentage(((b1.divide(b2,2,BigDecimal.ROUND_HALF_UP)).doubleValue() *100 ) + "%");
                }
            }
            for (int j = 0; j <list.size() ; j++) {
                if(StringUtils.equals(list.get(j).getStartTime(),lastSixMonths[i])){
                    VOList.add(list.get(j));
                }
            }
            //
            Double totalMoney = 0d;

            map.put(lastSixMonths[i],VOList);
            entity.setTime(lastSixMonths[i]);
            entity.setType(VOList);
            //获取每个月的总金额数
            for (CostStatisticsVO VO:VOList) {
                totalMoney = VO.getAccount();
            }
            entity.setTotalMoney(totalMoney);
            listEntity.add(entity);
        }
        returnMap.put("arr",listEntity);
        return returnMap;
    }

    @Override
    public ExpenseAccount selectExpenseAccountBy(Integer invoiceId) {
        return expenseAccountMapper.selectExpenseAccountBy(invoiceId);
    }

    @Override
    public Page<CostStatisticsDetailVO> queryCostStatisticsDetail(Page<CostStatisticsDetailVO> page, CostStatisticsQueryDTO queryDTO) {
        List<CostStatisticsDetailVO> list = expenseAccountMapper.queryCostStatisticsDetail(page, queryDTO);
        return page.setRecords(list);
    }

    @Override
    public Double queryDetailTotalMoney(CostStatisticsQueryDTO queryDTO) {
        return expenseAccountMapper.queryDetailTotalMoney(queryDTO);
    }

    @Override
    public List<CostStatisticsDetailExport> costStatisticsDetailExport(Map<String, Object> map) {
        return expenseAccountMapper.costStatisticsDetailExport(map);
    }
}
